package com.sd.repay.auth;

import com.sd.repay.common.CommonResult;
import com.sd.repay.common.Constants;
import com.sd.repay.pojo.RealAuthRecord;
import com.sd.repay.service.RealAuthService;
import com.sd.repay.utils.JsonUtil;
import com.sd.repay.utils.SpringUtil;
import com.sd.repay.utils.StringUtil;
import com.sd.repay.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 实现实名认证，路由后续完成
 */
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public class ImplRealAUth {

    private static Logger log = LoggerFactory.getLogger(ImplRealAUth.class);


    /**
     * 实现实名认证
     *
     * @param authParams
     * @return
     * @throws Exception
     */
    public static CommonResult toRealAuth(Map<String, String> authParams) throws Exception {

        log.info("实名认证参数：[{}]", new Object[]{JsonUtil.objectToJson(authParams)});

        String authType = authParams.get("authType");
        String realName = authParams.get("realName");
        String idCardNo = authParams.get("idCardNo");
        String accountNo = authParams.get("accountNo");
        String mobileNo = authParams.get("mobileNo");
        String defaultChannel = authParams.get("defaultChannel");

        if (StringUtil.isBlank(authType, realName, idCardNo)) {
            return CommonResult.build(403, "必要参数不能为空");
        }

        if (!Constants.AUTH_TYPE_TWO.equals(authType) && !Constants.AUTH_TYPE_THREE.equals(authType)
                && !Constants.AUTH_TYPE_FOUR.equals(authType)) {
            return CommonResult.build(403, "认证类型不合法");
        }

        RealAuthRecord authRecord = new RealAuthRecord();
        authRecord.setAuthType(authType);
        authRecord.setReanName(realName);
        authRecord.setIdCardNo(idCardNo);

        if (Constants.AUTH_TYPE_THREE.equals(authType)) {
            if (StringUtil.isBlank(accountNo)) {
                return CommonResult.build(403, "必要参数不能为空");
            }

            authRecord.setAccountNo(accountNo);
        }

        if (Constants.AUTH_TYPE_FOUR.equals(authType)) {
            if (StringUtil.isBlank(accountNo, mobileNo)) {
                return CommonResult.build(403, "必要参数不能为空");
            }

            authRecord.setAccountNo(accountNo);
            authRecord.setMobileNo(mobileNo);
        }

        RealAuthService realAuthService = SpringUtil.getBean("realAuthServiceImpl");
        RealAuthRoute realAuthRoute = SpringUtil.getBean("realAuthRoute");

        /**  是否存在已认证记录
         RealAuthRecord realAuthRecord = realAuthService.getRealAuthRecord(authRecord);
         if (realAuthRecord != null) {
         String status = realAuthRecord.getAuthStatus();
         String msg = realAuthRecord.getRespMsg();
         if ("1".equals(status)) {
         return CommonResult.ok();
         }
         return CommonResult.build(403, msg);
         }
         */
        String recordNo = WebUtil.nextUniqueSeqNo("t_real_auth_record", "AUTH", 20);
        String authChannel = realAuthRoute.getRealAuthChannel(defaultChannel, authType);
        if (StringUtils.isBlank(authChannel)) {
            return CommonResult.build(403, "无可用鉴权通道");
        }

        authRecord.setAuthChannel(authChannel);
        authParams.put("recordNo", recordNo);
        authParams.put("authChannel", authChannel);
        authParams.put("authSource", Constants.DEFAULT_OEM_TYPE);

        Long realAuthId = realAuthService.saveRealAuthRecord(authParams);
        log.info("实名认证参数：[{}]新增实名认证记录编号：[{}]", new Object[]{JsonUtil.objectToJson(authParams), realAuthId});
        if (realAuthId < 1) {
            return CommonResult.build(403, "新增实名认证记录失败");
        }

        RealAuthRecord newRealAuthRecord = realAuthService.getRealAuthRecord(String.valueOf(realAuthId));
        if (newRealAuthRecord == null) {
            return CommonResult.build(403, "未找到实名认证记录");
        }

        realAuthRoute.realAuth(newRealAuthRecord);
        log.info("实名认证参数：[{}]新增实名认证返回：[{}]", new Object[]{JsonUtil.objectToJson(authParams), JsonUtil.objectToJson(newRealAuthRecord.toJson())});
        String realStatus = newRealAuthRecord.getAuthStatus();
        String respCode = newRealAuthRecord.getRespCode();
        String respMsg = newRealAuthRecord.getRespMsg();
        int updateCount = 0;

        try {
            updateCount = realAuthService.updateRealAuthStatus(newRealAuthRecord);
        } catch (Exception e) {
            log.error("实名认证参数：[{}] 修改认证状态出现异常：{}", JsonUtil.objectToJson(authParams), e.getMessage());
        }

        log.info("实名认证参数：[{}] 认证状态[{}], 响应码[{}], 描述[{}], 受影响行数[{}]条", new Object[]{JsonUtil.objectToJson(authParams), realStatus, respCode, respMsg, updateCount});

        if ("1".equals(realStatus)) {
            return CommonResult.ok();
        }
        return CommonResult.build(403, respMsg);
    }
}